package com.hhxy.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.hhxy.handler.exception.CustomException;
import com.hhxy.model.dto.CategoryDto;
import com.hhxy.model.entity.Category;
import com.hhxy.model.vo.CategoryVo;
import com.hhxy.model.vo.ExcelCategoryVo;
import com.hhxy.service.CategoryService;
import com.hhxy.utils.BeanCopyUtils;
import com.hhxy.utils.WebUtils;
import com.hhxy.utils.response.AppHttpCodeEnum;
import com.hhxy.utils.response.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Objects;

/**
 * @author ghp
 * @date 2023/5/1
 * @title
 * @description
 */
@Api(tags = {"后端接口", "分类管理", "内容管理"})
@ApiSupport(author = "ghp", order = 1)
@RestController
@RequestMapping("/content/category")
@Validated
public class BeCategoryController {

    @Resource
    private CategoryService categoryService;

    @GetMapping("/list")
    @ApiOperation(value = "分页条件查询分类")
    @ApiOperationSupport(author = "ghp", order = 1)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页码", dataTypeClass = Integer.class, required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页大小", dataTypeClass = Integer.class, required = true),
            @ApiImplicitParam(name = "name", value = "分类名"),
            @ApiImplicitParam(name = "status", value = "分类状态 0-正常 1-审禁用")
    })
    public ResponseResult list(@NotNull(message = "pageNum不能为空") Integer pageNum,
                               @NotNull(message = "pageSize不能为空") Integer pageSize,
                               String name, String status) {
        return categoryService.list(pageNum, pageSize, name, status);
    }

    @DeleteMapping("/{ids}")
    @ApiOperation(value = "根据id删除分类")
    @ApiOperationSupport(author = "ghp", order = 1)
    @ApiImplicitParam(name = "ids", value = "分类id", dataType = "Long[]")
    public ResponseResult deleteCategoryByIds(@PathVariable @NotNull Long[] ids) {
        if (Objects.isNull(ids) || ids.length == 0) {
            throw new CustomException(AppHttpCodeEnum.CLIENT_ERROR);
        }
        return categoryService.deleteCategoryByIds(ids);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询分类")
    @ApiOperationSupport(author = "ghp", order = 1)
    @ApiImplicitParam(name = "id", value = "分类id", dataTypeClass = Long.class)
    public ResponseResult getCategoryById(@PathVariable @NotNull Long id) {
        return categoryService.getCategoryById(id);
    }

    @PutMapping
    @ApiOperation(value = "根据id修改分类")
    @ApiOperationSupport(author = "ghp", order = 1)
    public ResponseResult updateCategoryById(@RequestBody @Valid CategoryDto categoryDto) {
        return categoryService.updateCategoryById(categoryDto);
    }

    @PostMapping
    @ApiOperation(value = "新增分类")
    @ApiOperationSupport(author = "ghp", order = 1)
    public ResponseResult add(@RequestBody @Valid CategoryDto categoryDto) {
        return categoryService.add(categoryDto);
    }

    @GetMapping("/listAllCategory")
    @ApiOperation(value = "查询所有的分类", tags = "文章管理")
    @ApiOperationSupport(author = "ghp", order = 1)
    public ResponseResult getAllCategory(){
        List<CategoryVo> categoryVos = BeanCopyUtils.copyBeanList(categoryService.list(), CategoryVo.class);
        return ResponseResult.okResult(categoryVos);
    }

    @GetMapping("/export")
    @PreAuthorize("@ps.hasPermission('content:category:export')")
    @ApiOperation(value = "导出分类")
    @ApiOperationSupport(author = "ghp", order = 1)
    public void export(HttpServletResponse response){
        try {
            // 设置下载文件的请求头
            WebUtils.setDownLoadHeader("分类.xlsx",response);
            //获取需要导出的数据
            List<Category> categoryVos = categoryService.list();
            // 封装VO
            List<ExcelCategoryVo> excelCategoryVos = BeanCopyUtils.copyBeanList(categoryVos, ExcelCategoryVo.class);
            // 把数据写入到Excel中
            EasyExcel.write(response.getOutputStream(), ExcelCategoryVo.class).autoCloseStream(Boolean.FALSE).sheet("分类导出")
                    .doWrite(excelCategoryVos);
        } catch (Exception e) {
            // 如果出现异常也要响应json
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
            WebUtils.renderString(response, JSON.toJSONString(result));
        }
    }

}
